package com.zzyl.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.serve.domain.Elder;
import com.zzyl.serve.domain.FamilyMemberElder;
import com.zzyl.serve.dto.CheckInElderDto;
import com.zzyl.serve.dto.ElderDto;
import com.zzyl.serve.mapper.FamilyMemberElderMapper;
import com.zzyl.serve.service.FamilyMemberElderService;
import com.zzyl.serve.service.IElderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements FamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private IElderService elderService;
    @Override
    public int add(ElderDto dto) {
        //1.绑定信息不能为空
        //4.是否重复绑定
        Elder one = elderService.getOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, dto.getIdCard()));
        if (ObjectUtil.isNull(one)) {
            throw new BaseException("该老人不存在");
        }
        Long userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<FamilyMemberElder> eq = new LambdaQueryWrapper<FamilyMemberElder>()
                .eq(FamilyMemberElder::getElderId, one.getId())
                .eq(FamilyMemberElder::getFamilyMemberId, userId);
        long count = count(eq);
        if (count > 0){
            throw new BaseException("该老人已绑定");
        }
        //保存家属与老人的关系
        FamilyMemberElder familyMemberElder = BeanUtil.toBean(dto, FamilyMemberElder.class);
        familyMemberElder.setElderId(one.getId());
        familyMemberElder.setFamilyMemberId(UserThreadLocal.getUserId());
        return save(familyMemberElder) ? 1 : 0;



    }
}
